import React from "react";
import { Menu } from "antd";
import type { MenuProps } from "antd";
import { RouteRawState } from "../../types";
import { useNavigate, useLocation } from "react-router-dom";
import { useSelector } from "react-redux";
import { RootState } from "../../store";

type PropsType = {
  routes: RouteRawState[];
};

// 生成导航菜单函数
const generatorNavItems = (routes: RouteRawState[], role: string): MenuProps["items"] => {
  // 返回值是一个数组 数组类型
  return (
    routes
      // 过滤掉 不需要渲染出来的菜单  hidden = true
      .filter((v) => {
        if (v.hidden) {
          return false;
        } else {
          // 管理员 拥有所有
          if (role === "admin") return true;
          // 路由没有要求 所有人可以访问
          if (!v.meta.role) return true;
          // 当前用户是否符合路由权限要求
          return v.meta.role.includes(role);
        }
      })
      // 数据转换
      .map((v) => {
        return {
          key: v.path,
          label: v.meta.title,
          icon: v.meta.icon,
          // 递归调用 generatorNavItems， 生成多级菜单
          children: v.children && generatorNavItems(v.children, role),
        };
      })
  );
};

export const SliderNav: React.FC<PropsType> = ({ routes }) => {
  // 获取导航菜单
  const role = useSelector((state: RootState) => state.user.role)
  const items: MenuProps["items"] = generatorNavItems(routes, role);
  const navigate = useNavigate();
  const { pathname } = useLocation();
  return (
    <div>
      <Menu
        mode="inline"
        defaultSelectedKeys={[pathname]}
        defaultOpenKeys={["sub1"]}
        style={{ height: "100%", borderRight: 0 }}
        onClick={({ key }) => navigate(key)}
        items={items}
      />
    </div>
  );
};
